import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {Badge, Button, Card, Col, Divider, Form, Icon, Input, Modal, Row, Select, Steps} from 'antd';
import router from 'umi/router';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DirLine from "../sub/DirLine";
import styles from '../PrivateFile.less';
import DescriptionList from '@/components/DescriptionList';
import UploadFileForm from '../sub/UploadFileForm';
import SimpleDownloadApplyCreateForm from "../sub/SimpleDownloadApplyCreateForm";
import {getReadableSize, hasInstalledEditApp,} from '@/utils/dsrsUtil';
import ScanResultForm from "../sub/ScanResultForm";
import {getConfigs, getFileCodeToname} from '@/utils/bwdautil';
import wordIcon from '@/iconImg/word.png';
import excelIcon from '@/iconImg/excel.png';
import pptIcon from '@/iconImg/ppt.png';
import pdfIcon from '@/iconImg/pdf.png';
import zipIcon from '@/iconImg/zip.png';
import txtIcon from '@/iconImg/txt.png';
import picIcon from '@/iconImg/pic.png';
import csvIcon from '@/iconImg/csv.png';
import otherIcon from '@/iconImg/other.png';
import batIcon from '@/iconImg/bat.png';
import sqlIcon from '@/iconImg/sql.png';
import shIcon from '@/iconImg/sh.png';

const {Description} = DescriptionList;
const FormItem = Form.Item;
const {Step} = Steps;
const {TextArea} = Input;
const {Option} = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

/* eslint react/no-multi-comp:0 */
@connect(({groupModel, loading}) => ({
  groupModel,
  loading: loading.models.groupModel,
}))
@Form.create()
class GroupFiles extends PureComponent {

  state = {
    uploadModalVisible: false,
    downloadModalVisible: false,
    selectedRows: [],
    record: {},
    records: [],
    currentDirs: [{code: 'index', dirName: '我的文件库', id: ''}, {code: 'group_files', dirName: '自定义组文件'}],
    supportUploadFileTypes: "",//支持上传的文件类型  accept=".doc,.docx,"
    fileMaxUploadSize: "",//最大支持上传大小
    scanResultViewVisible: false,
  };

  columns = [
    {
      title: '文件名称',
      dataIndex: 'dirName',
      render: (text, row) => {
        if (row.dirType == 1) {
          return <Fragment>
            <Icon type="folder" theme="filled" style={{color: '#e87e04'}}/>&nbsp;
            <a onClick={() => this.openDir(row)}>{text}</a>&nbsp;
            {row.shareFlag == 1 ? <Icon type="share-alt" style={{color: '#40a9ff', cursor: 'pointer'}}
                                        onClick={() => this.shareViewHandelVisible(true, row)}
                                        title="共享详情"/> : null}&nbsp;
            {row.mostUseFlag == 1 ? <Icon type="star" style={{color: '#e87e04'}} title="收藏"/> : null}
          </Fragment>
        } else {
          let fielIcon = '';
          switch (row.fileSuffix) {
            case '.wps':
              case '.doc':
              case '.docx':
                fielIcon = wordIcon;             
                break;
                case '.txt':
                    fielIcon = txtIcon;
                    break;  
                case '.bat':             
                  fielIcon = batIcon;
                  break; 
                case '.sh':             
                  fielIcon = shIcon;
                  break;   
                case '.sql':             
                  fielIcon = sqlIcon;
                  break;     
              case '.ppt':
              case '.pptx':
                fielIcon = pptIcon;             
                break;          
              case '.xls':
              case '.xlsx':
                fielIcon = excelIcon; 
                break;   
              case '.pdf':
                fielIcon = pdfIcon; 
                break;
              case '.zip':
              case '.gz':
              case '.tar':
              case '.rar':
                fielIcon = zipIcon;              
                break;     
              case '.jpg':
              case '.png':
              case '.gif':
                fielIcon = picIcon;              
                break;  
              case '.csv':
                fielIcon = csvIcon;              
                  break;              
              default:
                fielIcon = otherIcon;
          }
          return <Fragment>
              <img src={fielIcon} />&nbsp;
            {text}&nbsp;
            {row.shareFlag == 1 ? <Icon type="share-alt" style={{color: '#40a9ff', cursor: 'pointer'}}
                                        onClick={() => this.shareViewHandelVisible(true, row)}
                                        title="共享详情"/> : null}&nbsp;
            {row.mostUseFlag == 1 ? <Icon type="star" style={{color: '#e87e04'}} title="收藏"/> : null}
          </Fragment>
        }

      },
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      render: (text, record) => {
        if (text) {
          return getReadableSize(text * 1024);
        } else {
          return '--'
        }
      },
    },
    {
      title: '敏感等级',
      dataIndex: 'secretLevelName',
    },
    {
      title: '状态',
      dataIndex: 'scanState',
      render:
        (val, record) => {
          let text = "--";
          let status = "";
          if (val == 0) {
            status = "processing";
            text = "未扫描";
          } else if (val == 1) {
            status = "processing";
            text = "扫描中";
          } else if (val == 2) {
            status = "success";
            text = <a onClick={() => this.queryScanResult(record)}>已扫描</a>;
          } else if (val == 3) {
            status = "error";
            text = "扫描失败";
          }else if (val == 4) {
            text = "无需扫描";
            status = "success";
          }
          return <Badge status={status} text={text}/>;


        }

    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render:
        val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      render:
        (text, record) => {

          const configs = getConfigs() || {};
          //文件
          if (record.dirType == 1) {
            return null
          } else if (record.dirType == 0) {
            return <Fragment>
              {configs.hidePreview ? null : <a onClick={() => this.previewItem(record.id)}>预览</a>}
              {configs.hidePreview ? null : <Divider type="vertical"/>}
              {configs.hideDownload ? null : <a onClick={() => this.queryDownloadRight(record)}>下载</a>}
            </Fragment>
          }
        },
    },
  ];

  componentDidMount() {
    let groupName = this.props.match.params.groupName;
    this.state.currentDirs.push({code: 'sub_file', dirName: groupName});


    this.querySubDirOrFileList()
    this.queryUpload();
    //自定义组管理员
    this.queryGroupAdmin();
  }

  queryGroupAdmin = () => {
    let groupId = this.props.match.params.groupId;
    const {dispatch} = this.props;
    let queryForm = {groupId: groupId};

    dispatch({
      type: 'groupModel/queryGroupAdmin',
      payload: queryForm,
    });
  };

  /**
   * 查询扫描结果
   * @param flag
   */
  queryScanResult = (record) => {
    const {dispatch} = this.props;
    const id = record.id;
    dispatch({
      type: 'groupModel/queryScanTree',
      payload: {id},
      callback: (res) => {

      },
    });

    this.handleScanResultModalVisible(true);

  };
  handleScanResultModalVisible = (flag,) => {
    this.setState({
      scanResultViewVisible: !!flag,
    });

  };

  backToRoot() {
    this.querySubDirOrFileList()
  }

  /**
   * 公共文件下载，暂不需要下载
   * @param record
   */
  queryDownloadRight = (record) => {

    let records = [];
    records.push(record);
    this.queryOptRight(0, records);

    // Modal.confirm({
    //   title: '下载',
    //   content: '您确定要下载吗？',
    //   okText: '确认',
    //   cancelText: '取消',
    //   onOk: () => this.quickDownload(record),
    // });
  }

  queryOptRight = (optType, records) => {

    const ids = records.map((item) => {
      return item.id;
    }).join(",");
    let payload = {ids, optType: optType};

    const {dispatch} = this.props;
    dispatch({
      type: 'privateFileModel/queryOptRight',
      payload: payload,
      callback: (res) => {
        if (res.result == "ok") {
          if (res.data.auditSetting == -1) {
            Modal.error({title: '操作失败', content: '您没有权限操作'});
            return;
          } else if (res.data.auditSetting == 1) {
            //需要审批
            this.auditOpt(optType, records);
          } else if (res.data.auditSetting == 0) {
            // 无需审批
            this.noneAuditOpt(optType, records);
          } else if (res.data.auditSetting == 2) {
            // 金库
            this.handleTreasuryVisible(true, optType, records);
          }
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }
  /**
   * 需要审核的操作
   * @param optType
   * @param ids
   */
  auditOpt = (optType, records) => {
    const ids = records.map((item) => {
      return item.id;
    }).join(",");
    //0 下载， 1流转  2外发，3共享 ， 4编辑
    switch (optType) {
      case 0:
        this.handleDownloadModalVisible(true, records);
        break;

      case 1:
        this.handleFlowModalVisible(true, records);
        break;
      case 2:
        this.handleOutModalVisible(true, records);
        break;
      case 3:
        this.handleShareModalVisible(true, records);
        break;
      case 3:
        this.handleEditModalVisible(true, records);
        break;
      default:
        break;
    }

  }

  /**
   * 无需审核的操作
   * @param optType
   * @param ids
   */
  noneAuditOpt = (optType, records) => {

    const ids = records.map((item) => {
      return item.id;
    }).join(",");
//0 下载， 1流转  2外发，3共享 ， 4编辑
    switch (optType) {
      case 0:
        this.confirmQuickDownload(records);
        break;
      case 1:
        this.quickFlow(records);
        break;
      case 2:

        this.quickOut(records);
        break;
      case 3:
        this.quickShare(records);
        break;
      case 4:
        this.quickEdit(records);
        break;
      default:
        break;
    }
  }


  confirmQuickDownload = records => {
    Modal.confirm({
      title: '下载',
      content: '您确定要下载吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.quickDownload(records),
    });
  }

  quickDownload = records => {

    const ids = records.map((item) => {
      return item.id;
    }).join(",");

    const {dispatch,} = this.props;
    dispatch({
      type: 'groupModel/quickDownloadGroupFiles',
      payload: {
        id: ids,
      },
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: "操作成功，请稍候至下载列表查看"});
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  /*****上传成功*****/
  handleUpload = () => {
    const {currentDir} = this.state;
    this.handleUploadModalVisible();
    this.backToRoot();
  };
  /**
   * 弹出框
   * @param flag
   */
  handleUploadModalVisible = flag => {
    this.setState({
      uploadModalVisible: !!flag,
    });
  };

  handleDirModalVisible = (flag, record) => {
    this.setState({
      dirModalVisible: !!flag,
      record: record || {},
    });
  };


  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {dispatch} = this.props;
    const {formValues} = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = {...obj};
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    let groupId = this.props.match.params.groupId;
    const params = {
      pageNum: pagination.current - 1,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
      parentId: 0,
      groupId: groupId,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'groupModel/queryFileDirByGroup',
      payload: params,
    });
  };

  openDir = record => {
    this.state.currentDirs.push({code: 'sub_file', dirName: record.dirName, id: record.id});
    this.querySubDirOrFileList(record.id);
  }
  //显示文件夹下级内容
  querySubDirOrFileList = id => {
    let groupId = this.props.match.params.groupId;
    const {dispatch} = this.props;
    let queryForm = {parentId: id ? id : 0, groupId: groupId};

    dispatch({
      type: 'groupModel/queryFileDirByGroup',
      payload: queryForm,
    });
  };

  //选中了目录
  onDirSelect = item => {

    console.error("item.code:" + item.code);
    switch (item.code) {
      case 'index':
        router.push('/filecenter/home-file');
        break;
      case 'public_files':
        router.push('/filecenter/public-file');
        break;
      case 'group_files':
        router.push('/filecenter/group');
        break;
      case 'sub_file':
        let currentDirs = this.state.currentDirs;
        let newDirs = [];
        for (let sub of currentDirs) {
          newDirs.push(sub);
          if (item.id && item.id == sub.id) {
            console.error("euqals: item:" + JSON.stringify(item));
            break;
          }
        }
        //更改当前的显示
        this.setState({currentDirs: newDirs});
        if (item.id) {
          //查询文件夹下的子文件
          this.querySubDirOrFileList({id: item.id});
        } else {
          this.querySubDirOrFileList();
        }


        break;
      default:
        break;
    }


  }


  /***预览文件**/
  previewItem = id => {
    //获取编辑地址
    const {dispatch} = this.props;
    dispatch({
      type: 'groupModel/getPreviewLinkPath',
      payload: {
        fileId: id,
      },
      callback: (res) => {
        if (res.result == "ok") {
          let path = res.data;
          if (path) {
            window.open(path, "_self");
          } else {
            Modal.error({title: '操作失败', content: "缺少路径，无法预览"});
          }
        } else {
          Modal.error({title: '操作失败', content: res.msg});
          /*  message.error(res.msg);*/
        }
      },
    });
  };


  deleteItem = id => {
    const {dispatch} = this.props;
    dispatch({
      type: 'groupModel/deleteFileOrDir',
      payload: {
        id: id,
      },
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.querySubDirOrFileList(0);
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });

  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (fieldsValue.fileStatus == "0") {
        fieldsValue.mostUseFlag = 1;
      } else if (fieldsValue.fileStatus == "1") {
        fieldsValue.shareFlag = 1;
      }
      const groupId = this.props.match.params.groupId;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
        parentId: 0,
        groupId: groupId
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'groupModel/queryFileDirByGroup',
        payload: values,

      });
    });
  };


  handleDownloadModalVisible = (flag, records) => {

    this.setState({
      downloadModalVisible: !!flag,
      records: records||[],
    });
  };

  addDownloadApply = (records, fields) => {
    const ids = records.map((item) => {
      return item.id;
    }).join(",");

    const {dispatch} = this.props;
    dispatch({
      type: 'groupModel/addDownloadApply',
      payload: {
        ids: ids,
        applyTitle: fields.applyTitle,
        applyReason: fields.applyReason,
        auditUserCode: fields.auditUserCode,
      },
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg, content: "请到下载列表查看"});

          /* message.success(res.msg + ",请到下载列表查看。");*/
          this.handleDownloadModalVisible();
        } else {
          /*message.error(res.msg)*/
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });

  };

  /**
   * 查询支持上传的参数
   */
  queryUpload = () => {
    const {dispatch} = this.props;
    let params = {};
    dispatch({
      type: 'privateFileModel/queryUpload',
      payload: params,
      callback: (res) => {
        if (res.result == "ok" && res.data) {


          let originsupportUploadType = res.data.supportUploadType;
          let fileMaxUploadSize = res.data.fileMaxUploadSize;
          this.setState({supportUploadFileTypes: originsupportUploadType});
          this.setState({fileMaxUploadSize: fileMaxUploadSize});
        } else {

        }
      },
    });


  };


  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="文件名称">
              {getFieldDecorator('dirName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          {/* <Col md={8} sm={24}>
            <FormItem label="文件状态">
              {getFieldDecorator('fileStatus')(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  <Option value="">--请选择--</Option>
                  <Option value="0">常用文件</Option>
                  <Option value="1">共享文件</Option>
                </Select>
              )}
            </FormItem>
          </Col>*/}

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {

    const {
      groupModel: {data, scanData, groupAdmin,},
      loading,
    } = this.props;
    const {
      selectedRows,
      uploadModalVisible,
      record,
      records,
      downloadModalVisible,
      dirModalVisible,
      currentDirs,
      supportUploadFileTypes,
      fileMaxUploadSize,
      scanResultViewVisible,
    } = this.state;
    const groupId = this.props.match.params.groupId;
    const downloadMethods = {
      addDownloadApply: this.addDownloadApply,
      handleModalVisible: this.handleDownloadModalVisible,
    };
    //上传文件
    const uploadMethods = {
      handleUpload: this.handleUpload,
      handleModalVisible: this.handleUploadModalVisible,
    };

    const scanResultMethods = {
      handleModalVisible: this.handleScanResultModalVisible,
    };
    return (
      <PageHeaderWrapper title="自定义组文件">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>

            <div className={styles.tableListOperator2}>

              <Button icon="upload" type="primary" onClick={() => this.handleUploadModalVisible(true)}>
                上传
              </Button>
              {/*<Button icon="plus" type="primary" onClick={() => this.handleDirModalVisible(true)}>*/}
              {/*新建文件夹*/}
              {/*</Button>*/}


            </div>

            <div style={{clear: 'both'}}></div>
            <div className={styles.filePath}>
              <DirLine dirs={currentDirs} onDirSelect={this.onDirSelect}/>
            </div>
            <TableList
              className={styles.tdPadding}
              hideRowSelection={true}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        {/*上传文件*/}
        <UploadFileForm {...uploadMethods} modalVisible={uploadModalVisible} currentDir={record} groupId={groupId}
                        supportUploadFileTypes={supportUploadFileTypes}
                        fileMaxUploadSize={fileMaxUploadSize}/>

        {/*申请下载文件*/}
        <SimpleDownloadApplyCreateForm {...downloadMethods} modalVisible={downloadModalVisible} records={records}
                                       orgAdmin={groupAdmin}/>
        <ScanResultForm {...scanResultMethods} modalVisible={scanResultViewVisible} scanData={scanData} />

      </PageHeaderWrapper>
    );
  }
}

export default GroupFiles;
